/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package predictor;

import java.awt.Component;
import java.awt.HeadlessException;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import weka.gui.ExtensionFileFilter;

/**
 *
 * @author Administrator
 */
public class MyFileChooser extends JFileChooser {

    public MyFileChooser(File currentDirectory, String strExtension, String strDescriptor) {
        super(currentDirectory);
        FileFilter modelFilter = new ExtensionFileFilter(strExtension, strDescriptor);
        this.setFileFilter(modelFilter);
        this.setAcceptAllFileFilterUsed(false);
        this.setFileSelectionMode(JFileChooser.FILES_ONLY);
        this.setMultiSelectionEnabled(false);
    }

    @Override
    public int showOpenDialog(Component parent) throws HeadlessException {
        int result = super.showOpenDialog(parent);
        if (result == APPROVE_OPTION) {
            if (!this.getSelectedFile().getAbsolutePath().endsWith(getExtension())) {
                this.setSelectedFile(new File(this.getSelectedFile().getAbsolutePath() + getExtension()));
            }
            if (!getSelectedFile().exists()) {
                JOptionPane.showMessageDialog(parent, "文件不存在!", "CBIB Predictor", JOptionPane.ERROR_MESSAGE);
                result = showOpenDialog(parent);
            }
        }
        return result;
    }

    private String getExtension() {
        return ((ExtensionFileFilter) this.getFileFilter()).getExtensions()[0];
    }

    @Override
    public int showSaveDialog(Component parent) throws HeadlessException {
        this.setSelectedFile(new File(this.getCurrentDirectory().getAbsolutePath() + "\\未命名" + getExtension()));
        int result = super.showSaveDialog(parent);

        if (result == APPROVE_OPTION) {
            if (!this.getSelectedFile().getAbsolutePath().endsWith(getExtension())) {
                this.setSelectedFile(new File(this.getSelectedFile().getAbsolutePath() + getExtension()));
            }
            if (!getSelectedFile().exists()) {
                return APPROVE_OPTION;
            }
            int retVal = JOptionPane.showConfirmDialog(
                    parent,
                    "文件 '"
                    + getSelectedFile()
                    + "' 已经存在 , 是否覆盖?");
            if (retVal == JOptionPane.YES_OPTION) {
                result = APPROVE_OPTION;
            } else if (retVal == JOptionPane.NO_OPTION) {
                result = showSaveDialog(parent);
            } else {
                result = CANCEL_OPTION;
            }
        }

        return result;
    }
}
